package com.momo.encoderHandler2;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;
import java.util.UUID;

/**
 * @author Kagome
 * @title: MyServerHandler
 * @projectName boot2.X-netty
 * @description: TODO
 * @date 2019/6/1 9:47
 */
public class MyServerHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private int count=0;
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        byte[] buffer = new byte[msg.readableBytes()];
        msg.readBytes(buffer);
        String msgStr = new String(buffer, Charset.forName("utf-8"));
        System.out.println("服务器端接收客户端数据：" + msgStr);
        System.out.println("服务器端接收客户端数据数量"+(++count));
        ByteBuf byteBuf = Unpooled.copiedBuffer(UUID.randomUUID().toString(), Charset.forName("utf-8"));
        ctx.writeAndFlush(byteBuf);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.getCause();
        ctx.close();
    }
}
